package com.example.qrcodecamera;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.util.List;

public class MaterialInfoDecodeActivity extends AppCompatActivity {
    private EditText etMaterialId, etMaterialnum, etweight, etvurweight;

    private MaterialDatabaseHelper dbHelper;
    private MaterialCSVDbHelper dbHelpercsv;

    private EditText etSearchMaterialId;
    private TextView tvQueryResult;
    private Button btnSearch, btnsavemysql, btnviewmysql;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_info_decode);

        dbHelper = new MaterialDatabaseHelper(this);
        dbHelpercsv = new MaterialCSVDbHelper(this);
        Button btnScan = findViewById(R.id.btn_scan);
        Button btnBack = findViewById(R.id.btn_back);
        Button btnsavemysql = findViewById(R.id.btn_save_mysql);
        Button btnviewmysql = findViewById(R.id.btn_view_mysqldata);
        etMaterialId = findViewById(R.id.et_material_id);
        etMaterialnum = findViewById(R.id.et_material_num);
        etweight = findViewById(R.id.et_weight);
        etvurweight = findViewById(R.id.et_curweight);

        btnScan.setOnClickListener(v -> {
            new IntentIntegrator(this)
                    .setPrompt("扫描物料信息二维码")
                    .setOrientationLocked(true)
                    .initiateScan();
        });

        btnBack.setOnClickListener(v -> finish());

        findViewById(R.id.btn_save).setOnClickListener(v -> {
            String id = etMaterialId.getText().toString().trim();
            String name = etMaterialnum.getText().toString().trim();
            String spec = etweight.getText().toString().trim();
            String weightStr = etvurweight.getText().toString().trim();

            if (id.isEmpty() || name.isEmpty() || spec.isEmpty() || weightStr.isEmpty()) {
                Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                boolean success = dbHelper.insertData(id, name, spec, weightStr);
                if (success) {
                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                    clearFields();
                } else {
                    Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "重量格式错误", Toast.LENGTH_SHORT).show();
            }
        });

        // 查看数据库按钮
        findViewById(R.id.btn_view_data).setOnClickListener(v -> {
            startActivity(new Intent(this, MaterialViewActivity.class));
        });


        etSearchMaterialId = findViewById(R.id.et_search_material_id);
        tvQueryResult = findViewById(R.id.tv_query_result);
        btnSearch = findViewById(R.id.btn_search);

        // 设置查询按钮点击事件
        btnSearch.setOnClickListener(v -> searchMaterialRecords());

        btnsavemysql.setOnClickListener(v -> {
            String id = etMaterialId.getText().toString().trim();
            String name = etMaterialnum.getText().toString().trim();
            String spec = etweight.getText().toString().trim();
            String weightStr = etvurweight.getText().toString().trim();

            if (id.isEmpty() || name.isEmpty() || spec.isEmpty() || weightStr.isEmpty()) {
                Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                boolean success = dbHelper.insertMYSQLData(id, name, spec, weightStr);
                if (success) {
                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                    clearFields();
                } else {
                    Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "重量格式错误", Toast.LENGTH_SHORT).show();
            }
        });

        btnviewmysql.setOnClickListener(v -> {
            startActivity(new Intent(this, MaterialViewActivity.class));
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null && result.getContents() != null) {
            String rawData = result.getContents();
            // 显示原始结果

            // 清理数据并拆分
            String cleanData = rawData.replaceAll("[{} ]", "");
            String[] parts = cleanData.split(",");

            if (parts.length == 4) {
                etMaterialId.setText(parts[0].trim());
                etMaterialnum.setText(parts[1].trim());
                //etweight.setText(parts[2].trim());
                String etweight1 = parts[2].trim().replaceAll("[^\\d.]", ""); // 移除非数字字符
                etweight.setText(etweight1); // 直接填充带单位的值（如 "97.00kg"）
                String rawWeight = parts[3].trim().replaceAll("[^\\d.]", ""); // 移除非数字字符
                etvurweight.setText(rawWeight); // 直接填充带单位的值（如 "97.00kg"）
                String number = parts[1].trim();
                searchMYSQLRecordsByNumber(number);
            } else {
                Toast.makeText(this, "二维码格式错误，需包含4个字段", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void clearFields() {
        etMaterialId.setText("");
        etMaterialnum.setText("");
        etweight.setText("");
        etvurweight.setText("");
    }

    private void searchMaterialRecords() {
        String materialId = etSearchMaterialId.getText().toString().trim();
        if (materialId.isEmpty()) {
            Toast.makeText(this, "请输入物料编号", Toast.LENGTH_SHORT).show();
            return;
        }

        List<MaterialInfo> records = dbHelper.getmysqlMaterialById(materialId);
        if (records.isEmpty()) {
            tvQueryResult.setText("未找到相关记录");
            resetEditTextBackgrounds();
            return;
        }

        // 取最新一条记录
        MaterialInfo record = records.get(0);
        String dbId = record.getMaterialId();
        String dbweight = record.getGrossWeight();
        String dbcurWeight = record.getNetWeight();
        String dbtime = record.getStorageTime();

        // 获取当前输入框内容
        String inputId = etSearchMaterialId.getText().toString().trim(); // 正确引用查询输入框
        String inputweight = etweight.getText().toString().trim();
        String inputCurweight = etvurweight.getText().toString().trim();


        // 重置背景颜色
        resetEditTextBackgrounds();


        if (!inputweight.equals(dbweight)) {
            etweight.setBackgroundResource(R.drawable.edittext_border_red);
        }
        if (!inputCurweight.equals(dbcurWeight)) {
            etvurweight.setBackgroundResource(R.drawable.edittext_border_red);
        }

        // 显示查询结果
        StringBuilder result = new StringBuilder();
        result.append("最新记录：\n")
                .append("入库时间: ").append(dbtime).append("\n")
                .append("物料编号: ").append(dbId).append("\n")
                .append("总重量: ").append(dbweight).append("\n")
                .append("现存重量: ").append(dbcurWeight);
        tvQueryResult.setText(result.toString());
    }

    private void resetEditTextBackgrounds() {
        etMaterialId.setBackgroundResource(R.drawable.edittext_border);
        etMaterialnum.setBackgroundResource(R.drawable.edittext_border);
        etweight.setBackgroundResource(R.drawable.edittext_border);
        etvurweight.setBackgroundResource(R.drawable.edittext_border);
    }


    private void searchMYSQLRecordsByNumber(String materialId) {
        UserDao userDao = new UserDao(this);
        userDao.materialqueryByBatchNumber(materialId, new UserDao.materialQueryResultCallback() {
            @Override
            public void onSuccess1(List<MaterialInfocsv> records) {
                runOnUiThread(() -> {
                    if (records.isEmpty()) {
                        tvQueryResult.setText("未找到相关记录");
                        resetEditTextBackgrounds();
                        return;
                    }

                    // 获取当前输入框内容
                    String inputId = etMaterialId.getText().toString().trim();
                    String inputWeight = etweight.getText().toString().trim().replaceAll("[^\\d.]", "");
                    String inputCurWeight = etvurweight.getText().toString().trim().replaceAll("[^\\d.]", "");

                    // 取最新一条记录
                    MaterialInfocsv record = records.get(0);
                    String dbId = record.getMaterialId();
                    String dbWeight = record.getGrossWeight(); // 对应grossWeight字段
                    String dbCurWeight = record.getNetWeight();  // 对应netWeight字段
                    String dbTime = record.getStorageTime();

                    // 重置背景颜色
                    resetEditTextBackgrounds();

                    // 数值比较逻辑（带容差0.001）
                    try {
                        if (!inputWeight.isEmpty() && !dbWeight.isEmpty()) {
                            double inputVal = Double.parseDouble(inputWeight);
                            double dbVal = Double.parseDouble(dbWeight);
                            if (Math.abs(inputVal - dbVal) > 0.001) {
                                etweight.setBackgroundResource(R.drawable.edittext_border_red);
                            }
                        }
                    } catch (NumberFormatException e) {
                        etweight.setBackgroundResource(R.drawable.edittext_border_red);
                    }

                    try {
                        if (!inputCurWeight.isEmpty() && !dbCurWeight.isEmpty()) {
                            double inputVal = Double.parseDouble(inputCurWeight);
                            double dbVal = Double.parseDouble(dbCurWeight);
                            if (Math.abs(inputVal - dbVal) > 0.001) {
                                etvurweight.setBackgroundResource(R.drawable.edittext_border_red);
                            }
                        }
                    } catch (NumberFormatException e) {
                        etvurweight.setBackgroundResource(R.drawable.edittext_border_red);
                    }

                    // 显示查询结果
                    StringBuilder result = new StringBuilder();
                    result.append("入库时间: ").append(dbTime).append("\n")
                            .append("物料编号: ").append(dbId).append("\n")
                            .append("总重量: ").append(dbWeight).append("\n")
                            .append("现存重量: ").append(dbCurWeight);
                    tvQueryResult.setText(result.toString());
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                runOnUiThread(() -> {
                    Toast.makeText(MaterialInfoDecodeActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                    tvQueryResult.setText("查询失败");
                });
            }


        });
    }
}